package com.jews.securityleam.authentication;

import com.jews.securityleam.authentication.sms.SmsAuthenticationProvider;
import com.jews.securityleam.authentication.sms.SmsLoginProcessFilter;
import com.jews.securityleam.starter.base.CustomAuthenticationFailureHandler;
import com.jews.securityleam.starter.base.CustomAuthenticationSuccessHandler;
import com.jews.securityleam.starter.base.JwtAuthenticationEntryPoint;
import com.jews.securityleam.starter.config.SecurityCommonProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.header.writers.frameoptions.XFrameOptionsHeaderWriter;
import org.springframework.web.cors.CorsUtils;

@Configurable
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, proxyTargetClass = true)
@ComponentScan(value = {"com.jews.securityleam.starter.base", "com.jews.securityleam.starter.config"})
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private SecurityCommonProperties commonProperties;

    @Autowired
    private JwtAuthenticationEntryPoint unauthorizedHandler;

    @Autowired
    private CustomAuthenticationFailureHandler failureHandler;

    @Autowired
    private CustomAuthenticationSuccessHandler successHandler;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private SmsAuthenticationProvider smsAuthenticationProvider;

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        // AuthenticationManager 下有List<AuthenticationProvider>
        // 通过 AuthenticationManagerBuilder add 进去
        auth.authenticationProvider(smsAuthenticationProvider);
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    /**
     * 使用BCrypt强哈希方法来加密密码
     */
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);
        web.ignoring().antMatchers(HttpMethod.GET,
                "/",
                "/*.html",
                "/favicon.ico",
                "/**/*.html", "/**/*.css",
                "/**/*.js");
    }

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.requiresChannel()
                .anyRequest().requiresInsecure()
                .and()
                .csrf().disable()//csrf取消
                .cors().disable()
                .exceptionHandling().authenticationEntryPoint(unauthorizedHandler)
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()//不再存储session
                .headers().frameOptions().disable()
                .and()
                .headers().addHeaderWriter(
                        new XFrameOptionsHeaderWriter(XFrameOptionsHeaderWriter.XFrameOptionsMode.SAMEORIGIN))
                .and()
                .authorizeRequests()
                .requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
                .antMatchers(HttpMethod.OPTIONS).permitAll()
                .antMatchers(HttpMethod.GET,
                        "/",
                        "/*.html",
                        "/favicon.ico",
                        "/**/*.html", "/**/*.css",
                        "/**/*.js").permitAll()
                .antMatchers("/public/**").permitAll()
                .antMatchers("/auth/**").permitAll()
                .antMatchers(commonProperties.getUnAuthUrls()
                        .toArray(new String[commonProperties.getUnAuthUrls().size()])).permitAll()
                .anyRequest().authenticated();

        httpSecurity
                .addFilterBefore(smsFilter(), UsernamePasswordAuthenticationFilter.class)
//                .addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class)
        ;

        httpSecurity.headers().cacheControl();
    }

    public SmsLoginProcessFilter smsFilter() {
        return new SmsLoginProcessFilter(authenticationManager, successHandler, failureHandler);
    }
}
